<template>
  <div class="account-box">
    <div class="toggle">
      <a
        href="javascript:;"
        v-if="!isAccountLogin"
        @click="isAccountLogin = !isAccountLogin"
      >
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a href="javascript:;" v-else @click="isAccountLogin = !isAccountLogin">
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <Form
      class="form"
      :validation-schema="rules"
      ref="FormCom"
      v-slot="{ errors }"
    >
      <template v-if="isAccountLogin">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field
              name="account"
              v-model="form.account"
              type="text"
              placeholder="请输入用户名或手机号"
            />
          </div>
          <!-- 错误提示信息 -->
          <div class="error" v-if="errors.account">
            <i class="iconfont icon-warning" />
            {{ errors.account }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <Field
              name="password"
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
            />
          </div>
          <!-- 错误提示信息 -->
          <div class="error" v-if="errors.password">
            <i class="iconfont icon-warning" />
            {{ errors.password }}
          </div>
        </div>
      </template>
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field
              name="mobile"
              v-model="form.mobile"
              type="text"
              placeholder="请输入手机号"
            />
          </div>
          <!-- 错误提示信息 -->
          <div class="error" v-if="errors.mobile">
            <i class="iconfont icon-warning" />
            {{ errors.mobile }}
          </div>
        </div>

        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <Field
              name="code"
              v-model="form.code"
              type="password"
              placeholder="请输入验证码"
            />
            <span class="code" @click="sendCode()" v-if="totalTime === 0"
              >发送验证码</span
            >
            <span class="code" v-else>{{ totalTime }}s</span>
          </div>
          <!-- 错误提示信息 -->
          <div class="error" v-if="errors.code">
            <i class="iconfont icon-warning" />
            {{ errors.code }}
          </div>
        </div>
      </template>
      <div class="form-item">
        <div class="agree">
          <Field as="XtxCheckbox" name="isAgree" v-model="form.isAgree">
          </Field>
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <!-- 错误提示信息 -->
        <div class="error" v-if="errors.isAgree">
          <i class="iconfont icon-warning" />
          {{ errors.isAgree }}
        </div>
      </div>
      <a href="javascript:;" class="btn" @click="submit">登录</a>
    </Form>
    <div class="action">
      <!-- 这里是用于配合下面的window.QC.Login弹出一个框 -->
      <!-- <span id="qqLoginBtn"></span> -->
      <!-- 拿到弹出框的链接地址自定义放在A标签 -->
      <!-- https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback -->
      <a @click.prevent="qqClick" href="#">
        <img
          src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png"
          alt=""
        />
        <span id="qqLoginBtn"></span>
      </a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onUnmounted } from "vue";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import { Form, Field } from "vee-validate";
import validObj from "@/utils/vee-validate-schema";
import {
  userMobileLoginMsg,
  userAccountLogin,
  userMobileLogin,
} from "@/api/user";
import Message from "@/components/library/Message";
import { useIntervalFn } from "@vueuse/core";
export default {
  components: {
    Form,
    Field,
  },
  // vue2写法
  // created(){
  //   this.$message({type: "error",text: "用户名已存在"})
  // },
  setup() {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    const isAccountLogin = ref(true);
    const form = reactive({
      account: "",
      password: "",
      mobile: "",
      code: "",
      isAgree: false,
    });
    // 表单验证规则
    const rules = {
      // name为account的Field
      account: validObj.account,
      password: validObj.password,
      mobile: validObj.mobile,
      code: validObj.code,
      isAgree: validObj.isAgree,
    };
    const FormCom = ref(null);

    // 点击登录
    const submit = async () => {
      const valid = await FormCom.value.validate();
      if (valid) {
        try {
          let data = null;
          if (isAccountLogin.value == true) {
            // 账号登录
            const { account, password } = form;
            data = await userAccountLogin({ account, password });
          } else {
            // 手机号登录
            // 发送验证码
            const { mobile, code } = form;
            data = await userMobileLogin({ mobile, code });
          }
          // 存储用户信息
          const { id, account, avatar, mobile, nickname, token } = data.result;
          store.commit("user/setUser", {
            id,
            account,
            avatar,
            mobile,
            nickname,
            token,
          });
          // 跳转到原页面或者首页
          router.push(route.query.redirectUrl || "/");
          // 消息提示
          Message({
            type: "success",
            text: "登录成功",
          });
        } catch (e) {
          console.dir(e);
          Message({
            type: "error",
            text: e.message || "登录失败",
          });
        }
      }
      //   .then(async (res) => {
      //     if (res) {
      //       // 帐号密码登录 (xiaotuxian001 123456     zhousg 123456)
      //       if (isAccountLogin.value) {
      //         await store.dispatch("user/getUserInfo", form);
      //       } else {
      //         // 手机短信验证登录
      //         await store.dispatch("user/getUserInfoByPhone", form);
      //       }
      //       Message({
      //         type: "success",
      //         text: "登录成功",
      //       });
      //       // 跳转到原页面或者首页
      //       router.push(route.query.redirect || "/");
      //     } else {
      //       Message({
      //         type: "error",
      //         text: "登录失败",
      //       });
      //     }
      //   });
    };

    const totalTime = ref(0);
    // pause 暂停 resume 开始
    // useIntervalFn(回调函数 ，执行间隔 ， 是否立即开启 )
    const { pause, resume } = useIntervalFn(
      () => {
        totalTime.value--;
        if (totalTime.value <= 0) {
          pause();
        }
      },
      1000,
      false
    );
    onUnmounted(() => {
      pause();
    });
    // 发送验证码
    const sendCode = async () => {
      // 局部验证
      const result = rules.mobile(form.mobile);
      if (result === true) {
        if (totalTime.value === 0) {
          // 调用api发送验证码
          await userMobileLoginMsg(form.mobile);
          Message({
            type: "success",
            text: "发送成功",
          });
          totalTime.value = 60;
          resume();
        }
      } else {
        // 显示红色错误
        FormCom.value.setFieldError("mobile", result);
      }
    };

    // 点击使用QQ登录
    function qqClick() {
      // 记录从哪个页面进来的
      store.commit("user/setRedirect", route.query.redirect || "/");

      // 这个网址是下面的window.QC.Login拿到的
      window.location.href =
        "https://graph.qq.com/oauth2.0/show?which=Login&display=pc&client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback";
    }

    // onMounted(() => {
    //   // 组件渲染完毕，使用QC生成QQ登录按钮
    //   window.QC.Login({
    //     btnId: 'qqLoginBtn'
    //   })
    // })

    return {
      isAccountLogin,
      form,
      rules,
      FormCom,
      submit,
      sendCode,
      totalTime,
      qqClick,
    };
  },
};
</script>
<style lang="less" scoped>
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
